package com.example.article.service.impl;

import com.example.article.entity.ArticleEntity;
import com.example.article.service.ArticleService;
import com.example.article.vo.ArticleEntityVo;
import com.example.commonutils.JwtUtils;
import com.example.commonutils.ResultData;
import com.example.commonutils.constants.MqConstants;
import com.example.servicebase.exceptionhandler.CustomException;
import io.netty.util.internal.StringUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public ResultData saveArticle(ArticleEntity article) {
        if (!StringUtils.hasText(article.getUserId())) {
            return ResultData.error().message("请先登录");
        }
        if (StringUtils.hasText(article.getMdContent()) && StringUtils.hasText(article.getSummary()) && StringUtils.hasText(article.getTitle())) {
            article.setGmtCreate(new Date());
            article.setViewCount(0l);
            mongoTemplate.save(article, "article");
        } else {
            return ResultData.error().message("请将信息填写完整");
        }
        rabbitTemplate.convertAndSend(MqConstants.ARTICLE_EXCHANGE,MqConstants.ARTICLE_INSERT_KEY,article.getId());
        return ResultData.ok();
    }

    @Override
    public ResultData getArticleCommentInfo(Integer page, Integer limit, String sort, HttpServletRequest request) {
        //从请求中获取token
        String token = JwtUtils.getMemberIdByJwtToken(request);
        String memberId = "";
        if (!StringUtil.isNullOrEmpty(token)) {
            memberId = JwtUtils.getMemberIdByJwtToken(request);
        }
        //根据课程id去查询文章表
        Query query = new Query();
        //判断查询条件 1表示按时间降序 2表示按浏览数降序 3表示只看我自己的
        if ("1".equals(sort)) {
            query.with(Sort.by(
                    Sort.Order.desc("gmtCreate")
            ));
        } else if ("2".equals(sort)) {
            query.with(Sort.by(
                    Sort.Order.desc("viewCount")
            ));
        } else if ("3".equals(sort)) {
            query = new Query(Criteria.where("userId").is(memberId));
        }
        query.skip((page - 1) * limit).limit(limit);
        List<ArticleEntity> articles = mongoTemplate.find(query, ArticleEntity.class, "article");
        List<ArticleEntityVo> result = articles.stream().map(article -> {
            ArticleEntityVo articleEntityVo = new ArticleEntityVo();
            BeanUtils.copyProperties(article, articleEntityVo);
            return articleEntityVo;
        }).collect(Collectors.toList());
        long size = mongoTemplate.count(new Query(), ArticleEntity.class, "article");
        return ResultData.ok().data("articles", result).data("size", size);
    }

    @Override
    public ResultData getArticleById(String articleId) {
        ArticleEntity article = mongoTemplate.findById(articleId, ArticleEntity.class, "article");
        if (article != null && article.getViewCount() != null) {
            article.setViewCount(article.getViewCount() + 1);
        } else {
            article.setViewCount(1l);
        }
        mongoTemplate.save(article, "article");
        return ResultData.ok().data("article", article);
    }

    @Override
    public ResultData deleteArticleById(String articleId, HttpServletRequest request) {
//        //从请求中获取token
//        String token = JwtUtils.getMemberIdByJwtToken(request);
//        String memberId = "";
//        if (!StringUtil.isNullOrEmpty(token)) {
//            memberId = JwtUtils.getMemberIdByJwtToken(request);
//            ArticleEntity articleEntities = mongoTemplate.findOne(new Query(Criteria.where("id").is(articleId)), ArticleEntity.class, "article");
//            if (memberId.equals(articleEntities.getUserId())){
//                throw new CustomException(2001,"无法删除他人的文章");
//            }
//        }else{
//            throw new CustomException(20001,"请登录");
//        }
        Query query = new Query(Criteria.where("id").is(articleId));
        mongoTemplate.remove(query, ArticleEntity.class, "article");
        rabbitTemplate.convertAndSend(MqConstants.ARTICLE_EXCHANGE,MqConstants.ARTICLE_DELETE_KEY,articleId);
        return ResultData.ok();
    }
}
